package com.example.mydemo;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.mydemo.utils.StorageUtils;

import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StartMainActivity extends AppCompatActivity {
    private String phoneNumber;
    private Button buttonSubmit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.startactivity);
        initView();
        initListener();
        // 检查目的联系人是否存在
        phoneNumber = StorageUtils.getString(StartMainActivity.this);
        if (!TextUtils.isEmpty(phoneNumber)) {
            Intent intent = new Intent(StartMainActivity.this, MainActivity.class);
            intent.putExtra(StorageUtils.KEY, phoneNumber);
            StorageUtils.setValue(phoneNumber);
            startActivity(intent);
        }
    }

    private void initListener() {
        buttonSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText textView = findViewById(R.id.number);
                String number = textView.getText().toString();
                //设置Value
                StorageUtils.setValue(number);
                //保存键值对
                StorageUtils.saveString(StartMainActivity.this);
                phoneNumber = StorageUtils.getString(StartMainActivity.this);
                if (validatePhoneNumber(phoneNumber)) {
                    Intent intent = new Intent(StartMainActivity.this, MainActivity.class);
                    intent.putExtra("PHONE_NUMBER", phoneNumber);
                    startActivity(intent);
                } else {
                    Toast.makeText(StartMainActivity.this, "请输入有效的电话号码", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    private void initView() {
        buttonSubmit = findViewById(R.id.buttonSubmit);
    }
    //判断是不是全球号码
    public boolean validatePhoneNumber(String phoneNumber) {
        if (phoneNumber == null || phoneNumber.isEmpty()) {
            return false;
        }
        // 去掉前后的空格
        phoneNumber = phoneNumber.trim();
        // 定义符合E.164标准的正则表达式
        String regex = "^\\+?[1-9]\\d{1,14}$";

        // 使用正则表达式进行匹配
        boolean matches = phoneNumber.matches(regex);
        return matches;
    }
}